<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<meta name="Developer" content="Pascal Kriete" />
		<title>SimplyPost Install</title>
		
		<style type="text/css" media="screen">
		<!--
			body {
				font-family: "Trebuchet MS", Helvetica;
			}
			
			.hidden {
				display: none;
			}

			.tip {
				background: #ddf;
				font-size: 80%;
				padding: 5px;
				border: 1px solid #00a;
			}
			
			.note {
				background: #fdd;
				font-size: 80%;
				padding: 5px;
				border: 1px solid #a00;
			}
			
			.welcome {
				background: #ddf;
				font-size: 90%;
				padding: 5px;
				width: 500px;
				display: block;
				border: 1px solid #00a;	
			}
			
			.warning {
				background: #fdd;
				font-size: 90%;
				padding: 5px;
				width: 500px;
				display: block;
				border: 1px solid #a00;	
			}
			
			.button {
				color: #fff;
				width: 5em;
				background: #333;
				border: 1px solid #888;
			}
			
			#toggle {
				font-size: 80%;
				color: #00a;
				cursor: pointer;
			}
			
			#content {
				width: 500px;
				margin-left: auto;
				margin-right: auto;
			}
			
			table {
				width: 500px;
			}
			
			table h3 {
				border-bottom: 1px dotted black;
				margin-bottom: 10px;
			}
		-->
		</style>
		
		<script src="./assets/js/mootools.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" charset="utf-8">
		<!--
			/*init = function() {
				$$('.tip').invoke('hide');
				$('toggle').removeClassName('hidden');
				$('toggle').observe('click', toggle_help);
				$('next').observe('submit', check);
				
				$('url').observe('blur', function() {
					var ur = $('url').value;
					if (ur.charAt(ur.length - 1) != '/')
						$('url').value = ur + '/';
				});
			}
			
			toggle_help = function() {
				$$('.tip').invoke('toggle');
			}
			
			check = function(event) {
				if($('password').value != $('pass_conf').value) {
					event.stop();
					alert('Password does not match confirmation');
				}
			}*/
			
			init = function() {
				$('toggle').removeClass('hidden');
				myFx = []
				$$('.tip').each(function(e) {
					myFx.push(new Fx.Slide(e).hide());
				});
				
				$('toggle').addEvent('click', function() {
					myFx.each(function(e) {
						e.toggle();
					});
				});
				
				$('next').addEvent('submit', check);
				$('url').addEvent('blur', function() {
					var ur = $('url').value;
					if (ur.charAt(ur.length - 1) != '/')
						$('url').value = ur + '/';
				});
			}
			
			check = function(evt) {
				evt = new Event(evt);
				if($('password').value != $('pass_conf').value) {
					evt.stop();
					alert('Password does not match confirmation');
				}
			}
			
			window.addEvent('domready', init);
		//-->
		</script>
	</head>
<body>

<div id="content">

<h1>SimplyPost</h1>

<?php

class Installer {

	var $version = "0.3.7";

	// If you change this... WRITE IT DOWN!!
	var $enc_key = "Vz3iWZ9hOVwRKW0p0zyRaTS58McwlItW";
	
	function Installer()
	{
		if (isset($_POST['go']))
			$this->stepOne();
		elseif (isset($_POST['get_db']))
			$this->stepTwo();
		elseif (isset($_POST['finalize']))
			$this->stepThree();
		else
			$this->start();		
	}

	function start()
	{
		if (version_compare(PHP_VERSION, '5.0.0') < 0):
		?>
		<h2>Server Incompatible</h2>
		
		<div class="warning">
		SimplyPost is written for use with PHP 5.<br/>
		Your server does not meet this requirement.
		
		<p>
			The PHP Group officially dropped PHP 4 support at the end of 2007, three years
			after releasing PHP 5.  To avoid more incompatibility issues in the future, 
			talk to your host about upgrading to the latest version.
		</p>
		</div>
		<?php
		
		else:
		
		?>
		<h2>Installation Wizard</h2>
		<form action="./index.php" method="post" accept-charset="utf-8">

		<input type="hidden" name="go" value="1">
		<noscript>
		<div class="warning">
		SimplyPost requires administrators to have javascript enabled.
		</div>
		</noscript>
		<div class="welcome">
		We need to know a few things about your server before you can use SimplyPost.
		Use the help function if you are unsure what to put into each field.<br/>
		Let's get started:<br/>
			<p style="text-align: center; margin:0;"><input type="submit" value="Begin!" class="button"></p>
		</div>
		</form>

		<p>Installation Step 1 of 3</p>
		<?php
		
		endif;
	}
	
	function stepOne()
	{

		$protocol = $_SERVER['HTTPS'] ? 'https://' : 'http://';
		$root = $_SERVER['SERVER_NAME'];
		$port = $_SERVER['SERVER_PORT'] == '80' ? '' : ':'.$_SERVER['SERVER_PORT'];
		$file = $_SERVER['SCRIPT_NAME'];

		$current = $protocol.$root.$port.$file;
		$file = end(explode('/', $current));

		$server = $current;

		switch($file) {
			case 'index.php':
				$server = substr($current, 0, -9);
				break;
			case 'install.php':
				$server = substr($current, 0, -11);
				break;
			default:
		}
		
		?>
		<p id="toggle" class="hidden">Toggle Help</p>
		<form action="" method="post" accept-charset="utf-8" id="next" name="next">
			
			<table border="0">
				<tr class="tip">
				<td colspan="2">
					<strong>What do I put here?</strong><br/>
					Check with your hosting provider if you do not know where to obtain some of this information.
				</td>
				</tr>
				
				<tr>
					<td colspan="2">
						<h3>Server Information</h3>
					</td>
				</tr>
				
				<tr>
					<td><label for="url">Server Address: </label></td>
					<td><input type="text" name="url" value="<?php echo $server; ?>" id="url"></td>
				</tr>
				<tr class="tip">
				<td colspan="2">
					The complete server address to the folder where this installation file resides.<br/>
					Most of the time our guess is pretty good.  Make sure to include a trailing slash.
				</td>
				</tr>
				<tr>
					<td><label for="htaccess">Create .htaccess file</label></td>
					<td><input type="checkbox" name="htaccess" id="htaccess" CHECKED></td>
				</tr>
				<tr class="tip">
				<td colspan="2">
					If checked, SimplyPost will create a .htaccess file in this directory.  Uncheck this if you have your own.
				</td>
				</tr>

				<tr>
					<td colspan="2">
						<h3>Database</h3>
					</td>
				</tr>
				<tr class="note">
				<td colspan="2">
					Ensure that the database name is unique. It will be created if it does not exist.<br/>
					Any existing tables may be cleared. <strong>Beware!</strong>
				</td>
				</tr>
				
				<tr>
					<td><label for="host">DB Host: </label></td>
					<td><input type="text" name="host" value="localhost" id="host"></td>
				</tr>
				<tr class="tip">
				<td colspan="2">
					Your database host.  On local installations this is almost always localhost.
				</td>
				</tr>
				
				<tr>
					<td><label for="db">DB Name: </label></td>
					<td><input type="text" name="db" value="" id="db"></td>
				</tr>
				<tr class="tip">
				<td colspan="2">
					The name of the database that SimplyPost will use.
				</td>
				</tr>
				
				<tr>
					<td><label for="username">DB Username: </label></td>
					<td><input type="text" name="username" value="" id="username"></td>
				</tr>
				<tr class="tip">
				<td colspan="2">
					Your database username.
				</td>
				</tr>
				
				<tr>
					<td><label for="password">DB Password</label></td>
					<td><input type="text" name="password" value="" id="password"></td>
				</tr>
				<tr class="tip">
				<td colspan="2">
					Your database password.
				</td>
				</tr>
				
				<tr>
					<td><input type="hidden" name="get_db" value="1"></td>
					<td><input type="submit" value="Next Step"></td>
				</tr>
			</table>
		</form>

		<p>Installation Step 2 of 3</p>
		<?php
	}
	
	function stepTwo()
	{

		//Simplify it
		$url = $_POST['url'];
		$host = $_POST['host'];
		$db = $_POST['db'];
		$un = $_POST['username'];
		$pw = $_POST['password'];

		// Good, now let's check this stuff

		// Trailing Slash?
		if (substr($url, -1, 1) != '/')
			$url.='/';

		// DB Connection
		$db_con = mysql_connect($host, $un, $pw);
		if (!$db_con)
			die('Database Connection Failed!');

		//Ok, let's make that db
		mysql_query("CREATE DATABASE ".$db, $db_con);

		//Select it
		mysql_select_db($db) or die(mysql_error());


		//Get sql file
		$src = realpath(dirname(__FILE__))."/simply_post.sql";
		$sql = file_get_contents($src);

		if (!$sql)
			die('cannot open sql file');

		// Run the CREATE commands
		$matches = array();
		$pattern = '/CREATE.+?;/si';
		preg_match_all($pattern, $sql, $matches);

		foreach($matches[0] as $query) {
			$tmp = substr($query, 0, -1);
			mysql_query($tmp, $db_con) or die(mysql_error());
		}

		// Run the INSERT commands
		$matches = array();
		$pattern = '/INSERT.+?;/si';
		preg_match_all($pattern, $sql, $matches);

		foreach($matches[0] as $query) {
			$tmp = substr($query, 0, -1);
			mysql_query($tmp, $db_con) or die(mysql_error());
		}

		// We got here, so let's fill up the configs

		// First we need that folder
		$path = APPPATH.'sp_conf';

		if (!is_dir($path))
		{
			mkdir($path);
		}

		// Deny directory listing
		$indexFile = $path.'/index.html';
		$handle = fopen($indexFile, 'w') or die('Cannot write to sp_conf directory.');
		
		ob_start();
		?>
<html>
<head>
	<title>403 Forbidden</title>
</head>
<body bgcolor='#ffffff'>
	<p>Directory access is forbidden.<p>
</body>
</html>
		<?php
		
		$data = ob_get_clean();
		fwrite($handle, $data);
		fclose($handle);

		// Now the conf file
		$confFile = $path.'/conf_tmp.php';
		$handle = fopen($confFile, 'w') or die('Cannot create config file.');

		ob_start();
		?>
$config['sp_version'] = "<?php echo $this->version; ?>";
$config['base_url']	= "<?php echo $url; ?>";
$config['encryption_key'] = "<?php echo $this->enc_key; ?>";
		<?php

		$data = "<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); \n\n" . ob_get_clean() . "\n ?>";

		fwrite($handle, $data);
		fclose($handle);

		// And the db file
		$dbFile = $path.'/db_tmp.php';
		$handle = fopen($dbFile, 'w') or die('Cannot create db config file.');

		ob_start();
		?>
$db['default']['hostname'] = "<?php echo $host; ?>";
$db['default']['username'] = "<?php echo $un; ?>";
$db['default']['password'] = "<?php echo $pw; ?>";
$db['default']['database'] = "<?php echo $db; ?>";
		<?php

		$data = "<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); \n\n" . ob_get_clean() . "\n ?>";

		fwrite($handle, $data);
		fclose($handle);
		
		// .htaccess if they want it
		if (isset($_POST['htaccess']))
		{
			$htFile = './.htaccess';
			$handle = fopen($htFile, 'w') or die('Cannot create .htaccess file.');

			ob_start();
			?>
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|application|system|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]
			<?php

			$data = ob_get_clean();

			fwrite($handle, $data);
			fclose($handle);
		}

		?>
		<p class="note">
			Core Setup Successful!
		</p>

		<p id="toggle" class="hidden">Toggle Help</p>
		<form action="" method="post" accept-charset="utf-8" id="next" name="next">
			
		<table border="0">
			<tr>
				<td colspan="2">
					<h3>Board Information</h3>
				</td>
			</tr>
			
			<tr>
				<td><label for="title">Title: </label></td>
				<td><input type="text" name="title" value="Sample Board" id="title"></td>
			</tr>
			<tr class="tip">
			<td colspan="2">
				The title of your board.  This can be changed at any time.
			</td>
			</tr>
			
			<tr>
				<td colspan="2">
					<h3>Admin Credentials</h3>
				</td>
			</tr>
			
			<tr>
				<td><label for="login">Login Name: </label></td>
				<td><input type="text" name="login" value="admin" id="login"></td>
			</tr>
			<tr class="tip">
			<td colspan="2">
				The name you will use to login.  Normal users are required to use an email, you are not.
			</td>
			</tr>
			
			<tr>
				<td><label for="name">Display Name: </label></td>
				<td><input type="text" name="name" value="admin" id="name"></td>
			</tr>
			<tr class="tip">
			<td colspan="2">
				The display name other users will see.
			</td>
			</tr>
			
			<noscript>
				<tr class="note">
				<td colspan="2">
					The password confirmation currently uses javascript.  You have javascript turned off, so your password will not be verified.
				</td>
				</tr>
			</noscript>
			
			<tr>
				<td><label for="password">Password: </label></td>
				<td><input type="password" name="password" value="" id="password"></td>
			</tr>
			<tr class="tip">
			<td colspan="2">
				The password you want to use for the admin account.
			</td>
			</tr>
			
			<tr>
				<td><label for="pass_conf">Confirm Password: </label></td>
				<td><input type="password" name="pass_conf" value="" id="pass_conf"></td>
			</tr>
			<tr class="tip">
			<td colspan="2">
				The password again.
			</td>
			</tr>
			
			<tr>
				<td><input type="hidden" name="finalize" value="1"></td>
				<td><input type="submit" value="Install"></td>
			</tr>
		</table>
		</form>

		<p>Installation Step 3 of 3</p>
		<?php
	}
	
	function stepThree()
	{
		$version = $this->version;

		$title = $_POST['title'];
		$name = $_POST['name'];
		$pw = $_POST['password'];
		$email = $_POST['login'];
		$joined = time();
		$post_count = 0;

		// Encrypt Password
		$salt = sha1($pw.$this->enc_key);
		$pw = sha1($salt.$email);

		// Get db settings
		include(APPPATH.'sp_conf/db_tmp.php');

		//Open connection
		$db_con = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
		mysql_select_db($db['default']['database']);

		$query = "INSERT INTO `general` (`id`,`title`,`locked`) VALUES ('1','".$title."','0')";
		mysql_query($query, $db_con);

		$query = "INSERT INTO `users` (`id`,`username`,`password`,`role`,`email`,`timezone`,`daylight_savings`,`joined`,`post_count`) VALUES ('1','".$name."','".$pw."','1','".$email."','UP1',NULL,'".$joined."','".$post_count."')";
		mysql_query($query, $db_con);

		//And we're ready to go ...
		$path = APPPATH.'sp_conf/';
		rename($path.'db_tmp.php', $path.'db.php');
		rename($path.'conf_tmp.php', $path.'conf.php');

		?>
		<h2>Installation Completed</h2>

		<p class="welcome">Install was successful.  Get started by <a href="./member/login">logging in</a> using
			the password you just entered, and <strong><?php echo $email; ?></strong> as your e-mail address.
		</p>
		<p class="warning">
			You can now remove install.php from the main directory.  It is not needed anymore and poses a security risk if left in place.
		</p>
		<?php
	}

}

$install = new Installer();

?>

</div>
</body>
</html>